
let currentPage = 1


$("#commentList").on("click",".action-btn",function(){
	let commentId = $(this).prev().val()
	let state = $(this).text()
	deleteCommentB(commentId,state,currentPage)
})

$(".filter-select").on("change",function(){
	currentPage = 1
	queryAllCommentB()
})
$(".filter-input").on("input",function(){
	currentPage = 1
	queryAllCommentB()
})
queryAllCommentB()
function queryAllCommentB(pageNum = 1){
	let state = $(".filter-select").val()
	let title = $(".filter-input").eq(0).val()
	let userId = $(".filter-input").eq(1).val()
	let commentTotal = $("#commentList")
	$.ajax({
		url:"queryAllCommentB",
		type:"post",
		data:{
			state:state,
			pageNum:pageNum,
			title:title,
			userId:userId
		},
		success:function(data){
			commentTotal.empty()
			if(data.code == 200){
				let comments = data.data.data
				for(let i = 0;i<comments.length;i++){
					let comment = comments[i]
					
					let timeDiff = countTime(comment.createTime)
					
					let state = comment.state == 0?"已删除":"正常"
					let addStateClass = "status-normal"
					if(comment.state == 0){
						addStateClass = "status-deleted"
					}
					let addBtnClass = "delete"
					if(comment.state == 0){
						addBtnClass = ""
					}
					let BtnText = "删除"
					if(comment.state == 0){
						BtnText = "恢复"
					}
					let div = `
						<div class="comment-item">
	                        <div class="comment-user">
	                            <div class="user-avatar-small" style=" background: url(${comment.avatarUrl}) no-repeat;background-size: cover;"></div>
	                            <div class="user-info">
	                                <div class="username">${comment.userName}</div>
	                                <div class="user-id">ID：${comment.userId}</div>
	                            </div>
	                        </div>
	                        <div class="comment-content">
	                            <div class="comment-text">${comment.content}</div>
	                            <a href="#" class="comment-video" style="visibility:hidden;">${comment.videoTitle}</a>
	                        </div>
	                        <div class="comment-time">
	                            <i class="far fa-clock"></i> ${timeDiff}
	                        </div>
	                        <div class="comment-status">
	                            <span class="status-badge ${addStateClass}">${state}</span>
	                        </div>
	                        <div class="comment-actions">
	                        	<input type="hidden" value="${comment.commentId}">
	                            <button class="action-btn ${addBtnClass}">${BtnText}</button>
	                        </div>
	                    </div>
					`
					commentTotal.append(div)
				}
				makePageBar(data.data)
				$(".pagination").css("display","flex")
			}else{
				let div = `
					<div style="width: 148px;margin: 17% auto;">
	                	<img src="img/ZFZJ.svg">
	                	<p style="text-align: center">暂时没有评论哦~</p>
	                </div>
				`
				commentTotal.append(div)
				$(".pagination").css("display","none")
			}
		}
	})
}

function deleteCommentB(commentId,state,page){
	$.ajax({
		url:"deleteCommentB",
		type:"post",
		data:{
			commentId:commentId,
			state:state
		},
		success:function(data){
			if(data.code == 200){
				promptAnimation("评论"+state+"成功")
				queryAllCommentB(page)
			}else{
				promptAnimation("评论"+state+"失败")
			}
		}
	})
}

function makePageBar(page) {
	$(".batch-select input").prop("checked",false)
    let pageBar = $(".pagination");
    let navigatorNums = page.totalPageNum;
    pageBar.empty();
    
    
    let prevPage = $("<button><i class='fas fa-chevron-left'></i></button>").click(function() {
    	queryAllCommentB(currentPage - 1);
        currentPage--
    });
    pageBar.append(prevPage);

    for (let i = 0; i < navigatorNums.length; i++) {
        let num = navigatorNums[i];
        let pageLink = $("<button class='pagination-btn'>"+num+"</button>").click(function() {
        	queryAllCommentB(num);
            currentPage = num 
        });
        if (num == currentPage) {
            pageLink.addClass("active");
        }
        pageBar.append(pageLink);
    }

    let nextPage = $("<button><i class='fas fa-chevron-right'></i></button>").click(function() {
    	queryAllCommentB(currentPage + 1);
        currentPage++
    });
    pageBar.append(nextPage);
    

    if (!page.hasPrev) {
    	prevPage.prop("disabled",true)
    }
    if (!page.hasNext) {
    	nextPage.prop("disabled",true)
    }
}

function promptAnimation(text) {
    let $prompt = $("#prompt");
    $prompt.text(text);
    
    // 新增：立即停止所有正在进行的动画并重置位置
    $prompt.stop(true, true).css("top", "-60px");

    // 清除之前的定时器（防止动画堆积）
    if ($prompt.data('timeoutId')) {
        clearTimeout($prompt.data('timeoutId'));
    }

    // 上升动画
    $prompt.animate({ top: 0 }, {
        duration: 240,
        easing: "linear",
        complete: function() {
            // 保存新的定时器ID到元素数据
            const timeoutId = setTimeout(function() {
                // 下降动画（同样添加中断机制）
                $prompt.stop(true, true).animate({ top: -60 }, {
                    duration: 240,
                    easing: "linear",
                    complete: function() {
                        // 动画完成后清除定时器ID
                        $prompt.removeData('timeoutId');
                        if($("#videoDetailModal").hasClass("active")){
                        	closeVideoDetail()
                        }
                    }
                });
            }, 1500);
            
            // 存储定时器ID用于后续清除
            $prompt.data('timeoutId', timeoutId);
        }
    });
}

function countTime(time){
	// 计算时间差（毫秒）
	let diffMs = new Date() - new Date(time);
	 
	// 统一转换为分钟单位计算
	let diffMinutes = Math.floor(diffMs / (1000 * 60));
	let diffHours = Math.floor(diffMinutes / 60);
	let diffDays = Math.floor(diffHours / 24);
	 
	let timeStr;
	if (diffDays > 0) {
	    timeStr = `${diffDays}天前`;
	} else if (diffHours > 0) {
	    timeStr = `${diffHours}小时前`;
	} else if (diffMinutes > 0) {
	    timeStr = `${diffMinutes}分钟前`;
	} else {
	    timeStr = "刚刚";
	}
	
	return timeStr
}